package com.darkflame.client;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Logger;

import com.darkflame.client.interfaces.SSSGenericFileManager;
import com.darkflame.client.interfaces.SSSGenericFileManager.FileCallbackError;
import com.darkflame.client.interfaces.SSSGenericFileManager.FileCallbackRunnable;

/** This method is non-Gwt compatible, its use is only for real desktop Java apps **/

@GwtIncompatible("method is using java file handeling methods")
public class JavaFileManager implements SSSGenericFileManager{

	@GwtIncompatible("method is using java file handeling methods")
	static public JavaFileManager internalFileManager = new JavaFileManager();
	
	static Logger Log = Logger.getLogger("sss.JavaFileManager");
	
	@Override
	public void getText(String location,
			FileCallbackRunnable runoncomplete, FileCallbackError runonerror,
			boolean forcePost, boolean useCache) {
		// TODO Auto-generated method stub

	}

	@Override
	public void getText(String location,
			FileCallbackRunnable runoncomplete, FileCallbackError runonerror,
			boolean forcePost) {
		
		if (!location.contains("://")){
		   getLocalFile(location, runoncomplete, runonerror);
		} else {
		   getFromURL(location, runoncomplete, runonerror);
		}
		
		

	}

	private void getFromURL(String location,
			FileCallbackRunnable runoncomplete, FileCallbackError runonerror) {
		
		URL myUrl;
		try {
			myUrl = new URL(location);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			Log.info(" couldn't get remote file;"+e1.getLocalizedMessage());
			runonerror.run(e1.getLocalizedMessage(), e1);
			return;
		}
		


	    try {
	    	
		    BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    myUrl.openStream()));

		    String line="";
	    	String file="";
	    	
			while ((line = in.readLine()) != null){
				
				file=file+"\n"+line;
			    
			}
			  in.close();
			  
			  runoncomplete.run(file, 200);
			  
		} catch (IOException e) {
			Log.info(" couldn't get remote file;"+e.getLocalizedMessage());
			runonerror.run(e.getLocalizedMessage(), e);
		}

	  
		
	}

	private void getLocalFile(String location,
			FileCallbackRunnable runoncomplete, FileCallbackError runonerror) {
		Log.info(" getting file :"+location);
		//make absolute if needed

		Path fileloc =Paths.get(location);	
		
		if (fileloc.isAbsolute()){
				
			
		} else {
			Path currentRelativePath = Paths.get("");		
			Log.info(" getting file at currentRelativePath="+currentRelativePath.toAbsolutePath().toString());
			
			//not sure if slash is needed here
			String filepath = currentRelativePath.toAbsolutePath().toString() +"/"+ location;		
			
			fileloc = currentRelativePath.toAbsolutePath().resolve(filepath);
			
			
		}

		Log.info(" getting file at="+fileloc.toString());
		
		try {
			

			String contents = new String(Files.readAllBytes(fileloc));
		
			
			
			Log.info(" got contents="+contents);
			
			//fire runnable
			runoncomplete.run(contents, 200);
			
		} catch (IOException e) {
			
			
			Log.info(" couldn't get file;"+e.getLocalizedMessage());
			//Log.info("in "+currentRelativePath.toAbsolutePath().toString());
			//Log.info("filepath was = "+filepath);
		
			runonerror.run(e.getLocalizedMessage(), e);
			
		}
	}
	

	@Override
	public String getAbsolutePath(String relativepath) {
		
		//if its already absolute we just return it unchanged
		//eg c:\blahblah\blah.ntlist
		//or http:\\www.blahblah.com\blah\blah.ntlist
		//or http:\\blahblah.com\blah\blah.ntlist
		Log.info("get canonical name of:"+relativepath);
		
		//if its a web address ignore it
		if (relativepath.contains("://")||relativepath.startsWith("www.")){
						
			Log.info("path is likely a web address so we ignore");
			
			return relativepath;
			
		}
		
		//if it starts with a slash we add a dot in front to say its relative to the current directory and not route
		if (relativepath.startsWith("/")){
			relativepath="."+relativepath;
		}
		
		
		//if not then, as this is a Java and thus local we use File to get the absolute
		//path:		
		File f = new File(relativepath);

		try {
			String can = f.getCanonicalPath();
			Log.info("path now:"+can);

			return can;
		} catch (IOException e) {

			Log.severe("can not get canonical pathname of :"+relativepath+" "+e.getLocalizedMessage());
			return "ERROR_GETTING_CANONICAL PATHNAME";
		}
		
	}
	
}